package com.hcinfos.gsoo.ui;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.json.JSONObject;

import com.alipay.android.app.sdk.AliPay;
import com.hcinfos.gsoo.R;
import com.hcinfos.gsoo.config.Urls;
import com.hcinfos.gsoo.db.NewDBUtil;
import com.hcinfos.gsoo.enity.GdTakeAwayOrder;
import com.hcinfos.gsoo.enity.GdTakeAwayOrderDetail;
import com.hcinfos.gsoo.enity.OrderMsgEnity;
import com.hcinfos.gsoo.enity.User;
import com.hcinfos.gsoo.pay.Keys;
import com.hcinfos.gsoo.pay.Result;
import com.hcinfos.gsoo.pay.Rsa;
import com.hcinfos.gsoo.util.LogUtil;
import com.hcinfos.gsoo.util.SharePreferenceUtil;
import com.hcinfos.gsoo.util.UtilHttp;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 外卖订单详细
 * 
 * @author john
 * 
 */
public class WaimaiOrderDetailActivity extends Activity implements
		OnClickListener {

	private LinearLayout menu_ll;
	private List<String> list;
	private ImageView back_iv;
	private TextView pay_tv;

	private TextView name_tv;
	private TextView contact_tv;
	private TextView time_tv;
	private TextView total_tv;
	private TextView receiver_tv;
	private TextView receiver_phone_tv;
	private TextView address_tv;
	private TextView sendTime_tv;
	private TextView orderNum_tv;
	private TextView cancel_pay_tv;

	private String orderId;
	private ObjectMapper mapper;
	private List<GdTakeAwayOrderDetail> menuList;

	public final int OBTAIN_ORDERINFO_SUCCESS = 0x2200;
	public final int OBTAIN_ORDERINFO_FAIL = OBTAIN_ORDERINFO_SUCCESS + 1;
	public final int OBTAIN_MENUINFO_SUCCESS = OBTAIN_ORDERINFO_SUCCESS + 2;
	public final int OBTAIN_MENUINFO_FAIL = OBTAIN_ORDERINFO_SUCCESS + 3;
	public final int ONLINE_PAY_SUCCESS = OBTAIN_ORDERINFO_SUCCESS + 4;
	public final int ONLINE_PAY_FAIL = OBTAIN_ORDERINFO_SUCCESS + 5;
	public final int RQF_PAY = OBTAIN_ORDERINFO_SUCCESS + 6;
	private NewDBUtil dbUtil;
	private OrderMsgEnity msgOrder;
	private Context context;
	private SharePreferenceUtil util;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_waimaiorderdetail);
		util = new SharePreferenceUtil(this, "setting");

		context = this;
		dbUtil = NewDBUtil.newInstance(this);
		mapper = new ObjectMapper();
		menu_ll = (LinearLayout) findViewById(R.id.menu_ll);
		back_iv = (ImageView) findViewById(R.id.back_iv);
		back_iv.setOnClickListener(this);
		pay_tv = (TextView) findViewById(R.id.online_pay_tv);
		pay_tv.setOnClickListener(this);

		cancel_pay_tv = (TextView) findViewById(R.id.cancel_pay_tv);
		cancel_pay_tv.setOnClickListener(this);
		name_tv = (TextView) findViewById(R.id.name_tv);
		contact_tv = (TextView) findViewById(R.id.contact_tv);
		time_tv = (TextView) findViewById(R.id.time_tv);
		total_tv = (TextView) findViewById(R.id.total_tv);
		receiver_tv = (TextView) findViewById(R.id.receiver_tv);
		receiver_phone_tv = (TextView) findViewById(R.id.receiver_phone_tv);
		address_tv = (TextView) findViewById(R.id.address_tv);
		sendTime_tv = (TextView) findViewById(R.id.sendTime_tv);
		orderNum_tv = (TextView) findViewById(R.id.orderNum_tv);

		orderId = getIntent().getStringExtra("orderId");
		findOrderInfoById();
		obtainMenuById();
		user = (User) util.loadObject("user");
	}

	private User user;

	private void updateViews() {
		menu_ll.removeAllViews();
		if (menuList != null) {
			for (int i = 0; i < menuList.size(); i++) {
				GdTakeAwayOrderDetail detail = menuList.get(i);
				View view = LayoutInflater.from(this).inflate(
						R.layout.order_menu_item, null);
				TextView name_tv = (TextView) view.findViewById(R.id.name_tv);
				TextView price_tv = (TextView) view.findViewById(R.id.price_tv);
				TextView num_tv = (TextView) view.findViewById(R.id.num_tv);
				name_tv.setText(detail.getDishName());
				price_tv.setText("¥" + detail.getPrice());
				num_tv.setText(detail.getNum() + "份   ×");
				menu_ll.addView(view);
			}
		}

	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.back_iv:
			finish();
			break;
		case R.id.online_pay_tv:
			// payOrder();
			pay();
			break;
		case R.id.cancel_pay_tv:
			intent = new Intent(WaimaiOrderDetailActivity.this,
					MyWaimaiActivity.class);
			startActivity(intent);
			saveOrderMsg();
			finish();
			break;
		}
	}

	private GdTakeAwayOrder orderInfo;

	/**
	 * 根据订单id获取订单信息
	 */
	private void findOrderInfoById() {
		HttpUtils httpUtils = UtilHttp.getHttpUtils(this);
		RequestParams params = new RequestParams();
		params.addBodyParameter("record.id", orderId);
		params.addBodyParameter("prefix", "");
		httpUtils.send(HttpRequest.HttpMethod.POST, Urls.W_ORDRE_BY_ID, params,
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						LogUtil.e("wxf", "findOrderInfoById" + arg0.toString());
					}

					@Override
					public void onSuccess(ResponseInfo<String> text) {
						LogUtil.d("wxf", "findOrderInfoById=" + text.result);

						try {
							orderInfo = mapper.readValue(text.result,
									new TypeReference<GdTakeAwayOrder>() {
									});
							handler.sendEmptyMessage(OBTAIN_ORDERINFO_SUCCESS);

						} catch (Exception e) {
							handler.sendEmptyMessage(OBTAIN_ORDERINFO_FAIL);
						}

					}
				});
	}

	/**
	 * 根据订单号id 获取已点菜单信息
	 */

	private void obtainMenuById() {
		HttpUtils httpUtils = UtilHttp.getHttpUtils(this);
		RequestParams params = new RequestParams();
		params.addBodyParameter("beanProxy.orderId", orderId);
		httpUtils.send(HttpRequest.HttpMethod.POST, Urls.W_MENU_BY_ID, params,
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {

					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {

						try {
							JSONObject obj = new JSONObject(arg0.result);
							int state = obj.getInt("state");
							if (state == 200) {
								String rows = obj.getString("rows");
								menuList = mapper
										.readValue(
												rows,
												new TypeReference<List<GdTakeAwayOrderDetail>>() {
												});
								handler.sendEmptyMessage(OBTAIN_MENUINFO_SUCCESS);
							} else {
								handler.sendEmptyMessage(OBTAIN_MENUINFO_FAIL);

							}
						} catch (Exception e) {

						}

					}

				});
	}

	/**
	 * 支付订单
	 */
	private void payOrder() {
		HttpUtils httpUtils = UtilHttp.getHttpUtils(this);
		RequestParams params = new RequestParams();
		params.addBodyParameter("orderId", orderId);
		httpUtils.send(HttpRequest.HttpMethod.POST, Urls.W_SUBMIT_ORDER,
				params, new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						LogUtil.e("wxf", "payOrder" + arg0.toString());
						handler.sendEmptyMessage(ONLINE_PAY_FAIL);

					}

					@Override
					public void onSuccess(ResponseInfo<String> text) {
						LogUtil.d("wxf", "payOrder=" + text.result);
						try {
							JSONObject obj = new JSONObject(text.result);
							String message = obj.getString("message");
							int state = obj.getInt("state");
							if (state == 200) {
								handler.sendEmptyMessage(ONLINE_PAY_SUCCESS);
							} else {
								Message msg = handler.obtainMessage();
								msg.obj = message;
								msg.what = ONLINE_PAY_FAIL;
								handler.sendMessage(msg);

							}
						} catch (Exception e) {
							// 支付失败
							handler.sendEmptyMessage(ONLINE_PAY_FAIL);
						}

					}
				});
	}

	private Intent intent;
	Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {

			switch (msg.what) {
			case OBTAIN_ORDERINFO_SUCCESS:
				if (orderInfo == null)
					return;
				msgOrder = new OrderMsgEnity();
				name_tv.setText(orderInfo.getSuppNick());
				time_tv.setText("点餐时间 " + orderInfo.getAddDatetime());
				if (orderInfo.getUserNick() == null) {
					if (user != null)
						receiver_tv.setText("收件人： " + user.getTaName());
				} else {
					receiver_tv.setText("收件人： " + orderInfo.getUserNick());

				}
				receiver_phone_tv.setText("电话：" + orderInfo.getUserTelphone());
				address_tv.setText("地址：" + orderInfo.getArrivedAddr());
				receiver_phone_tv.setText("电话：" + orderInfo.getUserTelphone());
				orderNum_tv.setText("订单编号: " + orderInfo.getId());
				total_tv.setText("共计:" + orderInfo.getTotalNum() + "个菜，"
						+ orderInfo.getTotalPrice() + "元");
				msgOrder.setId(orderInfo.getId());
				msgOrder.setIsRead(0);
				msgOrder.setType(0);
				break;
			case OBTAIN_ORDERINFO_FAIL:

				break;
			case OBTAIN_MENUINFO_SUCCESS:
				updateViews();
				break;
			case OBTAIN_MENUINFO_FAIL:

				break;
			case ONLINE_PAY_SUCCESS:
				intent = new Intent(WaimaiOrderDetailActivity.this,
						MyWaimaiActivity.class);
				startActivity(intent);
				saveOrderMsg();
				finish();
				break;
			case ONLINE_PAY_FAIL:
				String errorMsg = "支付失败";
				if (msg.obj != null)
					errorMsg = msg.obj.toString();
				Toast.makeText(context, errorMsg, 500).show();
				break;
			case RQF_PAY:
				if (msg.obj != null) {
					Result result = new Result((String) msg.obj);
					String resultStr = result.getResult();
					result.parseResult();

					intent = new Intent(WaimaiOrderDetailActivity.this,
							MyWaimaiActivity.class);
					startActivity(intent);
					saveOrderMsg();
					finish();
					LogUtil.d("wxf", "resultStr=" + resultStr);
				}
				break;
			}
		};
	};

	public boolean onKeyDown(int keyCode, android.view.KeyEvent event) {

		intent = new Intent(WaimaiOrderDetailActivity.this,
				MyWaimaiActivity.class);
		startActivity(intent);
		saveOrderMsg();
		finish();
		return super.onKeyDown(keyCode, event);
	};

	private void saveOrderMsg() {
		if (msgOrder != null) {
			try {
				dbUtil.db.saveOrUpdate(msgOrder);
			} catch (DbException e) {
				LogUtil.e("wxf", "DbException=" + e.toString());
			}
		}

	}

	/**
	 * 支付宝支付模块
	 */
	private void pay() {
		String info = getOrderInfo();
		String sign = Rsa.sign(info, Keys.PRIVATE);
		sign = URLEncoder.encode(sign);
		info += "&sign=\"" + sign + "\"&" + getSignType();
		final String orderInfo = info;
		new Thread() {
			public void run() {
				AliPay alipay = new AliPay(WaimaiOrderDetailActivity.this,
						handler);

				// 设置为沙箱模式，不设置默认为线上环境
				// alipay.setSandBox(true);
				String result = alipay.pay(orderInfo);
				Message msg = handler.obtainMessage();
				msg.what = RQF_PAY;
				msg.obj = result;
				handler.sendMessage(msg);
				LogUtil.d("wxf", "result = " + result);
			}
		}.start();
	}

	private String getOrderInfo() {
		StringBuilder sb = new StringBuilder();
		sb.append("partner=\"");
		sb.append(Keys.DEFAULT_PARTNER);
		sb.append("\"&out_trade_no=\"");
		sb.append(orderId);
		sb.append("\"&subject=\"");
		sb.append("点餐订单");
		sb.append("\"&body=\"");
		sb.append("dfdsfdsfdsf");
		sb.append("\"&total_fee=\"");
		sb.append(orderInfo.getTotalPrice() + "");
		sb.append("\"&notify_url=\"");

		// 网址需要做URL编码
		sb.append(URLEncoder
				.encode("http://www.gsoo.com/alipaySupport_busi_callback.action"));
		sb.append("\"&service=\"mobile.securitypay.pay");
		sb.append("\"&_input_charset=\"UTF-8");
		sb.append("\"&return_url=\"");
		sb.append(URLEncoder.encode("http://m.alipay.com"));
		sb.append("\"&payment_type=\"1");
		sb.append("\"&seller_id=\"");
		sb.append(Keys.DEFAULT_SELLER);

		// 如果show_url值为空，可不传
		// sb.append("\"&show_url=\"");
		sb.append("\"&it_b_pay=\"1m");
		sb.append("\"");

		return new String(sb);
	}

	private String getSignType() {
		return "sign_type=\"RSA\"";
	}
}
